package com.jf.hotelreservation.demos.service.impl;

import com.alibaba.fastjson2.JSON;
import com.jf.hotelreservation.demos.bean.Hotel;
import com.jf.hotelreservation.demos.bean.Reservation;
import com.jf.hotelreservation.demos.bean.Room;
import com.jf.hotelreservation.demos.bean.vo.ReservationVo;
import com.jf.hotelreservation.demos.mapper.HotelMapper;
import com.jf.hotelreservation.demos.mapper.ReservationMapper;
import com.jf.hotelreservation.demos.mapper.RoomMapper;
import com.jf.hotelreservation.demos.service.ReservationService;
import com.jf.hotelreservation.demos.utils.DataUtils;
import com.jf.hotelreservation.demos.utils.PageBean;
import com.jf.hotelreservation.demos.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class ReservationServiceImpl implements ReservationService {

    @Autowired
    private ReservationMapper reservationMapper;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private HotelMapper hotelMapper;
    @Override
    public String addReservation(Reservation reservation) {
        reservation.setId(UUID.randomUUID().toString());
        int i = reservationMapper.addReservation(reservation);
        if (i != 0){
            return JSON.toJSONString(R.success("预约成功"));
        }else {
            return JSON.toJSONString(R.error("预约失败,请联系管理员"));
        }

    }

    @Override
    public String queryAll(Integer currentPage, Integer pageSize) {
        List<ReservationVo> reservationVoList = new ArrayList<>();
        List<Reservation> reservationList = reservationMapper.queryAll(DataUtils.getStartRecord(currentPage, pageSize), pageSize);
        // 循环遍历，根据房间ID 获取放假信息以及酒店信息
        for (Reservation reservation : reservationList) {
            ReservationVo reservationVo = new ReservationVo();
            Room room = roomMapper.queryById(reservation.getRoomId());
            Hotel hotel = hotelMapper.queryByRid(room.getId());
            BeanUtils.copyProperties(reservation,reservationVo);
            reservationVo.setRoom(room);
            reservationVo.setHotel(hotel);
            reservationVoList.add(reservationVo);
        }
        int count = reservationMapper.count();
        PageBean pageBean = new PageBean();
        pageBean.setTotal(count);
        pageBean.setRows(reservationVoList);
        return JSON.toJSONString(R.success("操作成功",pageBean));
    }
}
